package com.mflex.WHSmartWhouseAd.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.mflex.WHSmartWhouseAd.R;
import com.mflex.WHSmartWhouseAd.adapter.QMSReturnBoxAdapter;
import com.mflex.WHSmartWhouseAd.model.CommitSamplinginspectionModel;
import com.mflex.WHSmartWhouseAd.model.CommonRequest;
import com.mflex.WHSmartWhouseAd.model.QMSSamplingReturnPdaInfo;
import com.mflex.WHSmartWhouseAd.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

//import butterknife.BindView;
//import butterknife.ButterKnife;


public class QMSSamplingReturnActivity extends BaseActivity implements AdapterView.OnItemClickListener  {
    // 操作人员
    EditText stvOperator;
    // 载具码
    EditText stvVehicleCode;
    // 包号/盘号
    EditText stvPackageNumber;
    // 列表
    ListView lvList;
    // 清空
    Button buttonClear;
    // 提交
    Button buttonSubmit;

    // loading
    MiniLoadingDialog miniLoadingDialog;
    List<QMSSamplingReturnPdaInfo>QMSReturnModelList=new ArrayList<>();
    CommitSamplinginspectionModel model = new CommitSamplinginspectionModel();
    private String userName;
    private String materialtype;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_qms_sampling_return);
//        ButterKnife.bind(this);
        // 弹窗提示
        miniLoadingDialog =WidgetUtils.getMiniLoadingDialog(this,"加载...");
        //        id绑定
        stvOperator = findViewById(R.id.stv_Operator);
        stvVehicleCode = findViewById(R.id.stv_VehicleCode);
        stvPackageNumber = findViewById(R.id.stv_PackageNumber);
        lvList = findViewById(R.id.lvList);
        buttonClear = findViewById(R.id.button_clear);
        buttonSubmit = findViewById(R.id.button_submit);
        // 传递数据
        Intent intent = getIntent();
        userName = intent.getStringExtra("User");
        // 视图按键监听器
        stvPackageNumber.setOnKeyListener(this);
        stvVehicleCode.setOnKeyListener(this);
        buttonSubmit.setOnClickListener(this);
        buttonClear.setOnClickListener(this);
        stvVehicleCode.requestFocus();
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                QMSReturnModelList.clear();
                QMSReturnBoxAdapter QMSReturnBoxAdapter = new QMSReturnBoxAdapter(QMSSamplingReturnActivity.this,QMSReturnModelList);
                lvList.setAdapter(QMSReturnBoxAdapter);
                stvPackageNumber.setText("");
                stvVehicleCode.setText("");
                stvOperator.setText("");
                stvVehicleCode.requestFocus();
                break;
            case R.id.button_submit:
                saveButtonMd(view);
                break;
            default:
                break;
        }

    }
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_PackageNumber: // 包号/盘号
                     chekPackageNumber();
                    break;
                case R.id.stv_VehicleCode: // 载具号
                    chekVehicleCode();
                    break;
                default:
                    break;
            }
        }
        return false;
    }
    // 扫描载具码触发接口
    private void chekVehicleCode() {
        if(StringUtils.isEmpty(stvVehicleCode.getText().toString())) {
            return;
        }
        //      测试
//        QMSSamplingReturnPdaInfo people = new QMSSamplingReturnPdaInfo();
//        double adm =   Math.random();
//        people.setVehicleNumber("123"+adm);
//        people.setReelId("123456");
//        people.setTaskNo("任务单");
//        people.setMrart("料号");
//        List dataList = new ArrayList<>();
//        dataList.add(people);
//
//        QMSReturnModelList = dataList;
//        QMSReturnBoxAdapter QMSReturnBoxAdapter = new QMSReturnBoxAdapter(QMSSamplingReturnActivity.this,QMSReturnModelList);
//        lvList.setAdapter(QMSReturnBoxAdapter);

//      结束

        miniLoadingDialog.show();
        XHttp.get("api/WHSmartWhousePDA/GetQMInspectionData")
                .params("VehicleNumber",stvVehicleCode.getText().toString())
                .syncRequest(false)
                .onMainThread(true)
                .execute(new SimpleCallBack<List<QMSSamplingReturnPdaInfo>>() {
                    @Override
                    public  void  onSuccess(List<QMSSamplingReturnPdaInfo> response) {
                        miniLoadingDialog.dismiss();
                        QMSReturnModelList = response;
                        // 获取物料类型
                        materialtype = QMSReturnModelList.get(0).getMType();
                        if(QMSReturnModelList.isEmpty()) {
                            MediaPlayer mp = MediaPlayer.create(QMSSamplingReturnActivity.this,R.raw.error_voice);mp.start();
                            new MaterialDialog.Builder(QMSSamplingReturnActivity.this)
                                    .iconRes(R.drawable.icon_warning)
                                    .title(R.string.tip_warning)
                                    .content("查询归还列表为空！")
                                    .positiveText(R.string.lab_submit)
                                    .show();
                            return;
                        }
                        QMSReturnBoxAdapter QMSReturnBoxAdapter = new QMSReturnBoxAdapter(QMSSamplingReturnActivity.this,QMSReturnModelList);
                        lvList.setAdapter(QMSReturnBoxAdapter);
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        MediaPlayer mp = MediaPlayer.create(QMSSamplingReturnActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(QMSSamplingReturnActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }
                });

    }


//    箱号回车事件触发
    private void chekPackageNumber() {
        if(StringUtils.isEmpty(stvPackageNumber.getText().toString())) {
            return;
        }
        miniLoadingDialog.show();
        XHttp.get("api/WHSmartWhousePDA/CheckCode")
                .params("Code",stvPackageNumber.getText().toString())
                .syncRequest(false)
                .onMainThread(true)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public  void  onSuccess(String response) {
                        miniLoadingDialog.dismiss();
                        Log.d("1234",response);
                        for(QMSSamplingReturnPdaInfo item : QMSReturnModelList) {
                            // 跟列表包号匹配修改状态
                            if(Objects.equals(item.getReelId(), response)) {
                                item.setFlag("1");
                                item.setSizeReelId(stvPackageNumber.getText().toString());
                            };
                        }

                        QMSReturnBoxAdapter QMSReturnBoxAdapter = new QMSReturnBoxAdapter(QMSSamplingReturnActivity.this,QMSReturnModelList);
                        lvList.setAdapter(QMSReturnBoxAdapter);
                        stvPackageNumber.setText("");
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        MediaPlayer mp = MediaPlayer.create(QMSSamplingReturnActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(QMSSamplingReturnActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }
                });
    }
//    提交
    private void saveButtonMd(View v) {
        boolean isBtn = true;
        // 如果有未扫描的包号就设置为false
        if(!QMSReturnModelList.isEmpty()) {
            for( QMSSamplingReturnPdaInfo item : QMSReturnModelList) {
               if(StringUtils.equals("0",item.getFlag())) {
                   isBtn = false;
                   break;
               }
            }
        }else {
            MediaPlayer mp = MediaPlayer.create(QMSSamplingReturnActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(QMSSamplingReturnActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("载具码未输入")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }

        if(!isBtn) {
            MediaPlayer mp = MediaPlayer.create(QMSSamplingReturnActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(QMSSamplingReturnActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("归还失败！有未扫描的包号/盘标签")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        if(StringUtils.isEmpty(stvOperator.getText().toString())){
            MediaPlayer mp = MediaPlayer.create(QMSSamplingReturnActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(QMSSamplingReturnActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("操作人员未输入")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        List<CommitSamplinginspectionModel> dataList = new ArrayList<>();
        for( QMSSamplingReturnPdaInfo item : QMSReturnModelList) {
            CommitSamplinginspectionModel entity= new CommitSamplinginspectionModel();
            entity.setVehicleNumber(item.getVehicleNumber());
            // 半成品给大码
            if(Objects.equals(materialtype, "3")) {
                entity.setReelId(item.getSizeReelId());
            }else {
                entity.setReelId( item.getReelId());
            }
            entity.setERPlot(item.getERPlot());
            entity.setMPart(item.getMPart());
            entity.setMType(item.getMType());
            entity.setTaskNo(item.getTaskNo());
            entity.setUser(stvOperator.getText().toString());
            entity.setStatus(item.getStatus());
            entity.setGuid(item.getGuid());
            dataList.add(entity);
        }
//        CommonRequest request =new CommonRequest();
//        request.setJson(JsonUtil.toJson(dataList));
        String json = JsonUtil.toJson(dataList);
        Log.d("1234",json);
        miniLoadingDialog.show();
        XHttp.post("api/WHSmartWhousePDA/CommitReturnInspectionData")
                .upJson(JsonUtil.toJson(dataList))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String response) {
                        miniLoadingDialog.dismiss();
                        XToastUtils.success("提交成功",3000);
                        QMSReturnModelList.clear();
                        QMSReturnBoxAdapter QMSReturnBoxAdapter = new QMSReturnBoxAdapter(QMSSamplingReturnActivity.this,QMSReturnModelList);
                        lvList.setAdapter(QMSReturnBoxAdapter);
                        stvPackageNumber.setText("");
                        stvVehicleCode.setText("");
                        stvVehicleCode.requestFocus();
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        MediaPlayer mp =MediaPlayer.create(QMSSamplingReturnActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(QMSSamplingReturnActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }

                });
    }



    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
}